package com.xs.common.excel;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xs
 * date 2018/4/9 18:15
 */
public class ValidationUtils {

    /**
     * 使用hibernate的注解来进行验证
     */
    private static Validator validator = Validation
            .byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();

    /**
     * 功能描述: <br>
     * 〈注解验证参数〉
     *
     * @param obj
     * @see [相关类/方法](可选)
     */
    public static <T> String validateError(T obj) {
        String erroInfo = null;
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        // 抛出检验异常
        if (constraintViolations.size() > 0) {
            //校验每列数据
            erroInfo = validator.validate(obj).stream()
                    .map(ConstraintViolation::getMessageTemplate)
                    .collect(Collectors.joining("、"));

        }
        return erroInfo;
    }

}
